# -*- coding:utf-8 -*-
import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
from utils.HttpUtils import HttpUtils

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

class ShangCheng_PingLun():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            "User-Agent": ua.random,
        }

    def get_contents(self):
        postData = {
            "page": "0",
            "per_page": "10",
            "fold": "0",
            "tab": "2",
            "tag": "",
            "sid": "session.1572779772974525401812",
        }
        # url = "https://www.xiaohongshu.com/api/store/review/5b7a526970e7520da07599b5/product_review?page=0&per_page=10&tab=2&fold=0&tag=&sid=session.1572779772974525401812"
        url = "https://www.xiaohongshu.com/api/store/review/5b7a526970e7520da07599b5/product_review"
        html = HttpUtils.do_request("GET", url, self.headers, postData)
        datajson = json.loads(html.text)
        for d in datajson['data']['reviews']:
            dict_data = dict()
            dict_data['createTime'] = datetime.fromtimestamp(int(d['createTime']))
            dict_data['userInfo'] = d['userInfo']['userName']
            dict_data['userId'] = d['userInfo']['userId']
            dict_data['text'] = d['text']
            # 购买的商品
            dict_data['variants'] = d['variants']['name']
            dict_data['variants'] = d['variants']['value']


    # 封装请求方法
    def get_request(self, method, url, headers, data):
        # cookies = self.get_cookie_dict("JSESSIONID=D79B2E69AADDABD4A2A0B5352C4A1987")
        try:
            if method == "POST":
                if headers == "":
                    if url.find("https") == 0:
                        res = requests.post(url, data=data, verify=False)
                    else:
                        res = requests.post(url, data=data)
                else:
                    if url.find("https") == 0:
                        res = requests.post(url, headers=headers, data=data, verify=False)
                    else:
                        res = requests.post(url, headers=headers, data=data)
            elif method == "GET":
                if headers == "":
                    if url.find("https") == 0:
                        res = requests.get(url, params=data, verify=False)
                    else:
                        res = requests.get(url, params=data)
                else:
                    if url.find("https") == 0:
                        res = requests.get(url, headers=headers, params=data, verify=False)
                    else:
                        res = requests.get(url, headers=headers, params=data)
            else:
                res = None
        except Exception as ex:
            print("-------------访问错误------------")
            print(ex)
            return HttpUtils.do_request(method, url, headers, data)
        else:
            if res.status_code != 200:
                print(f"-------------返回状态码:{res.status_code}------------")
                return HttpUtils.do_request(method, url, headers, data)
        return res

    # 将cookies字符串转换dict格式
    def get_cookie_dict(self, str):
        itemDict = {}
        items = str.split(';')
        for item in items:
            arr = item.split('=')
            key = arr[0].replace(' ', '')
            value = arr[1]
            itemDict[key] = value
        return itemDict

if __name__ == '__main__':
    shangcheng_pinglun = ShangCheng_PingLun()
    shangcheng_pinglun.get_contents()